# -*- coding: utf-8 -*-
import os,sys,uuid,codecs,locale,multiprocessing
from flask import Flask
import datetime,time,copy,hashlib
import csv,json
import requests
from requests.auth import HTTPDigestAuth
import mysql.connector

'''
'''

app = Flask(__name__)

def setStrDefaultEncoding():
	reload(sys)
	sys.setdefaultencoding('utf-8')

def send_digest_auth_request():
	# 第一次请求，用于获取nonce和realm值
	username = ''
	password = ''
	url = ''
	response = requests.get(url)
	if response.status_code != 401:
		return None
	
	# 获取响应头中的WWW-Authenticate值
	www_auth_str = response.headers['WWW-Authenticate']
	www_auth_parts = www_auth_str.split(' ')
	#print(www_auth_parts)
	
	# 获取Digest认证所需的关键参数
	realm = www_auth_parts[1].split('realm=')[1].split(',')[0]
	nonce = www_auth_parts[1].split('nonce=')[1].split(',')[0]
	#print('realm: ', realm)
	#print('nonce: ', nonce)

	# 第二次请求，使用正确的认证头信息进行鉴权
	nonceCount = '00000001'
	clientNonce = '00000001'
	algorithm = 'MD5'
	qop = 'auth'

	# 组装A1
	a1 = f"{username}:{realm}:{password}"
	ha1 = hashlib.md5(a1.encode('utf8')).hexdigest()
	
	# 组装A2
	method = 'POST'
	a2 = f"{method}:{url}"
	ha2 = hashlib.md5(a2.encode('utf8')).hexdigest()
	
	# 组装响应摘要
	response = f"{ha1}:{nonce}:{nonceCount}:{clientNonce}:{qop}:{ha2}"
	ha3 = hashlib.md5(response.encode('utf8')).hexdigest()
	
	# 构造Digest认证头
	digest_auth_str = 'Digest username="{}", realm="{}", nonce="{}", uri="{}", algorithm="{}", qop="{}", nc="{}", cnonce="{}", response="{}", opaque="{}"'.format(username, realm, nonce, url, algorithm, qop, nonceCount, clientNonce, ha3, nonce)
	# 构造请求头
	headers = {
		'Authorization': digest_auth_str,
		'Content-Type': 'application/json',
		'cache-control': 'no-cache'
	}
	
	# 构造请求体
	data = {
		'type': 1
	}
	
	# 发送POST请求
	response = requests.post(url, headers=headers, json=data)
	
	# 解析响应数据
	if response.status_code == 200:
		#print(response.json())
		return response.json()
	else:
		print(response.status_code)

def build_tree(data):
	tree = []
	dirmap = {}
	devmap = []
	for dev in data['devList']:
		t = {}
		for key, value in dev.items():
			if isinstance(value, list):
				if len(value) > 1:
					print(233)
				else:
					if isinstance(value[0], dict):
						for key1, value1 in value[0].items():
							t[key1] = value1
			elif not isinstance(value, list) or not isinstance(value, dict):
				t[key] = value
		devmap.append(t)
	print(len(devmap))
	for node in data['groupList']:
		dirmap[node['groupId']] = node
		node['children'] = []
		node['dev'] = []
		for ndev in devmap:
			if node['groupId'] == ndev['groupId']:
				node['dev'].append(ndev)
		
	for node in data['groupList']:
		if node['parentId'] != '-1':
			parent = dirmap[node['parentId']]
			parent['children'].append(node)
		else:
			tree.append(node)
	return tree

def dfs(tree, dbdict, dblist, dp):
	xzjd = {}
	def getdata(ptd, dblist, dbdict):
		dbdict = copy.deepcopy(dbdict)
		dbdict['devId'] = ptd['devId']
		dbdict['cameraId'] = ptd['cameraId']
		dbdict['cameraName'] = ptd['cameraName']
		dbdict['status'] = ptd['status']
		dbdict['ptzType'] = ptd['ptzType']
		dbdict['longitude'] = ptd['longitude']
		dbdict['latitude'] = ptd['latitude']
		dbdict['altitude'] = ptd['altitude']
		dbdict['groupId'] = ptd['groupId']
		dblist.append(dbdict)
		
	if dp == 1:
		dbdict['ptmc'] = tree['groupName']
		dbdict['clientId'] = tree['clientId']
		dbdict['qxmc'] = ''
		dbdict['qxdm'] = 
		dbdict['xzmc'] = 'null'
		dbdict['xzdm'] = 'null'

	if len(tree['children']) > 0:
		for pt in tree['children']:
			if '' in pt['groupName']:
				dbdict['qxmc'] = pt['groupName']
				dbdict['qxdm'] = 510117
			if '街道' in pt['groupName'] or '镇' in pt['groupName'] or '派出所' in pt['groupName'] and pt['groupName'] != '**派出所':
				dbdict['xzmc'] = pt['groupName']
				dbdict['xzdm'] = xzjd[pt['groupName'][:2]]
			if len(pt['dev']) >= 1:
				for ptd in pt['dev']:
					getdata(ptd, dblist, dbdict)
			else:
				dp = dp + 1
				dfs(pt, dbdict, dblist, dp)
	else:
		if len(tree['dev']) >= 1:
			for ptd in tree['dev']:
				getdata(ptd, dblist, dbdict)
	
def excutesql(data):
	try:
		mydb = mysql.connector.connect(
			
		)
		#print(mydb)
		
		mycursor = mydb.cursor()
		mycursor.execute("delete from pd_jksbss_py;")
		mydb.commit()

		for row in data:
			if row['longitude'] == 'null' and row['latitude'] == 'null':
				geom = "POINT({} {})".format('0', '0')
				surround_geom = "POLYGON(({} {},{} {},{} {},{} {},{} {}))".format('0', '0', '0', '0', '0', '0', '0', '0', '0', '0')
				sql = "insert into pd_jksbss_py (GEOMETRY, SURROUNDGEOMETRY, PTMC, CLIENTID, QXMC, QXDM, XZMC, XZDM, DEVID, CAMERAID, CAMERANAME, STATUS, PTZTYPE, LONGITUDE, LATITUDE, ALTITUDE) VALUES (ST_PointFromText('{}'), ST_GeomFromText('{}'), '{}', '{}', '{}', {}, '{}', {}, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(geom, surround_geom, row['ptmc'], row['clientId'], row['qxmc'], row['qxdm'], row['xzmc'], row['xzdm'], row['devId'], row['cameraId'], row['cameraName'], row['status'], row['ptzType'], row['longitude'], row['latitude'], row['altitude'])
			else:
				geom = "POINT({} {})".format(row['longitude'], row['latitude'])
				surround_geom = "POLYGON(({} {},{} {},{} {},{} {},{} {}))".format(row['longitude'], row['latitude'], row['longitude'], row['latitude'], row['longitude'], row['latitude'], row['longitude'], row['latitude'], row['longitude'], row['latitude'])
				sql = "insert into pd_jksbss_py (GEOMETRY, SURROUNDGEOMETRY, PTMC, CLIENTID, QXMC, QXDM, XZMC, XZDM, DEVID, CAMERAID, CAMERANAME, STATUS, PTZTYPE, LONGITUDE, LATITUDE, ALTITUDE) VALUES (ST_PointFromText('{}'), ST_GeomFromText('{}'), '{}', '{}', '{}', {}, '{}', {}, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(geom, surround_geom, row['ptmc'], row['clientId'], row['qxmc'], row['qxdm'], row['xzmc'], row['xzdm'], row['devId'], row['cameraId'], row['cameraName'], row['status'], row['ptzType'], row['longitude'], row['latitude'], row['altitude'])
			#print('sql:', sql)
			mycursor.execute(sql)
			mydb.commit()
		
		mycursor.execute("select oid from pd_jksbss_py;")
		allrows = mycursor.fetchall()
		
		for r in allrows:
			#print('r: ', r[0], type(r[0]), '\n')
			mycursor.execute("select hex(GEOMETRY) from pd_jksbss_py where oid = '{}';".format(r[0]))
			geom_hex = mycursor.fetchone()[0]
			#print('geom_hex: ', geom_hex[0], type(geom_hex[0]), '\n')
			mycursor.execute("update pd_jksbss_py set GEOMETRY = (select unhex(ReplacePrefix('{}'))) where oid = '{}';".format(geom_hex, r[0]))
			mydb.commit()
		
	finally:
		#print(111)
		mydb.close()

@app.route('/WatchEquipment/watch/equipmentPointInfo')
def main():

	'''
	with open(u'./监控点位信息_一些挂在视频共享平台_一些在二级平台_一些在三级平台_一些在四级平台.json', 'r', encoding='utf-8') as f:
		data = json.load(f)
		t = build_tree(data)
		#print(t)
		l = []
		d = {}

		def spgxpt(l, d):
			d = copy.deepcopy(d)
			d['ptmc'] = t[0]['groupName']
			d['clientId'] = t[0]['clientId']
			d['qxmc'] = ''
			d['qxdm'] = 555555
			d['xzmc'] = 'null'
			d['xzdm'] = 'null'
			d['devId'] = devi['devId']
			d['cameraId'] = devi['cameraId']
			d['cameraName'] = devi['cameraName']
			d['status'] = devi['status']
			d['ptzType'] = devi['ptzType']
			d['longitude'] = devi['longitude']
			d['latitude'] = devi['latitude']
			d['altitude'] = devi['altitude']
			d['groupId'] = devi['groupId']
			l.append(d)

		# 监控设备全部挂在视频共享平台一级目录
		if len(t[0]['children']) == 0 and len(t[0]['dev']) > 0:
			for devi in t[0]['dev']:
				spgxpt(l, d)
		# 监控设备部分挂在视频共享平台一级目录，部分挂在下级目录
		elif len(t[0]['children']) > 0 and len(t[0]['dev']) > 0:
			# 挂在视频共享平台一级目录
			for devi in t[0]['dev']:
				spgxpt(l, d)
			# 挂在视频共享平台下级目录
			for pt in t[0]['children']:
				dp = 1
				d = copy.deepcopy(d)
				dfs(pt, d, l, dp)
		# 没有监控设备挂在视频共享平台一级目录
		elif len(t[0]['children']) > 0 and len(t[0]['dev']) == 0:
			for pt in t[0]['children']:
				dp = 1
				d = copy.deepcopy(d)
				dfs(pt, d, l, dp)

		print(l)
		#excutesql(l)
	'''

	t = build_tree(send_digest_auth_request())
	#print(t)
	l = []
	d = {}

	def spgxpt(l, d):
		d = copy.deepcopy(d)
		d['ptmc'] = t[0]['groupName']
		d['clientId'] = t[0]['clientId']
		d['qxmc'] = '**区'
		d['qxdm'] = 555555
		d['xzmc'] = 'null'
		d['xzdm'] = 'null'
		d['devId'] = devi['devId']
		d['cameraId'] = devi['cameraId']
		d['cameraName'] = devi['cameraName']
		d['status'] = devi['status']
		d['ptzType'] = devi['ptzType']
		d['longitude'] = devi['longitude']
		d['latitude'] = devi['latitude']
		d['altitude'] = devi['altitude']
		d['groupId'] = devi['groupId']
		l.append(d)

	# 监控设备全部挂在视频共享平台一级目录
	if len(t[0]['children']) == 0 and len(t[0]['dev']) > 0:
		for devi in t[0]['dev']:
			spgxpt(l, d)

	# 监控设备部分挂在视频共享平台一级目录，部分挂在下级目录
	elif len(t[0]['children']) > 0 and len(t[0]['dev']) > 0:
		# 处理挂在视频共享平台一级目录
		for devi in t[0]['dev']:
			spgxpt(l, d)
		# 处理挂在视频共享平台下级目录
		for pt in t[0]['children']:
			dp = 1
			d = copy.deepcopy(d)
			dfs(pt, d, l, dp)

	# 没有监控设备挂在视频共享平台一级目录
	elif len(t[0]['children']) > 0 and len(t[0]['dev']) == 0:
		for pt in t[0]['children']:
			dp = 1
			d = copy.deepcopy(d)
			dfs(pt, d, l, dp)
	
	#print(l)
	excutesql(l)
	return {'status': 1}
	
if __name__ == '__main__':
	app.run(port=18081, debug=True)
	#time1 = datetime.datetime.now()
	#print('start time: ', time1, '\n')
	#setStrDefaultEncoding()
	#main()
	#time2 = datetime.datetime.now()
	#print('end time: ', time2, '\n')
	#print('total time: ', time2 - time1, '\n')